package com.jzo2o.foundations.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.foundations.dto.response.ServeAggregationResDTO;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.mapper.*;
import com.jzo2o.foundations.model.domain.*;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.*;
import com.jzo2o.foundations.service.IServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 区域服务管理
 *
 * @author itcast
 * @create 2023/7/17 16:50
 **/
@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {

    @Autowired
    private ServeItemMapper serveItemMapper;
    @Autowired
    private RegionMapper regionMapper;

    /**
     * 区域服务分页
     *
     * @param servePageQueryReqDTO
     * @return
     */
    @Override
    public PageResult<ServeResDTO> findByPage(ServePageQueryReqDTO servePageQueryReqDTO) {
        return PageHelperUtils.selectPage(servePageQueryReqDTO,
                () -> baseMapper.queryList(servePageQueryReqDTO.getRegionId()));
    }

    /**
     * 区域服务新增
     *
     * @param serveUpsertReqDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(List<ServeUpsertReqDTO> serveUpsertReqDTO) {
        //遍历集合拿到每一个区域服务信息
        for (ServeUpsertReqDTO dto : serveUpsertReqDTO) {
            //1. 服务项目必须是启用状态的才能添加到区域
            //根据服务项目id查询serve_item得到服务项目状态
            ServeItem serveItem = serveItemMapper.selectById(dto.getServeItemId());
            if (ObjectUtil.isNull(serveItem) || serveItem.getActiveStatus() != 2) {
                throw new ForbiddenOperationException("添加失败,服务项目状态有误");
            }
            //2. 一个服务项目对于一个区域，只能添加一次
            Integer count = this.lambdaQuery().eq(Serve::getServeItemId, dto.getServeItemId())
                    .eq(Serve::getRegionId, dto.getRegionId())
                    .count();
            if (count > 0) {
                throw new ForbiddenOperationException("添加失败,当前服务项目已存在");
            }
            //向serve表进行数据保存
            Serve serve = BeanUtil.copyProperties(dto, Serve.class);
            //保存city_code字段根据region_id从region表中查询
            Region region = regionMapper.selectById(dto.getRegionId());
            if (ObjectUtil.isNotNull(region)) {
                serve.setCityCode(region.getCityCode());
            }
            baseMapper.insert(serve);
        }

    }

    /**
     * 区域服务删除
     *
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        //状态为草稿状态方可删除
        Serve serve = this.getById(id);
        if (ObjectUtil.isNull(serve) || serve.getSaleStatus() != 0) {
            throw new ForbiddenOperationException("删除失败, 当前区域服务不是草稿状态");
        }
        this.removeById(id);
    }

    /**
     * 区域服务上架
     *
     * @param id
     */
    @Override
    public void onSale(Long id) {
        //1) 区域服务当前非上架状态
        Serve serve = this.getById(id);
        if (ObjectUtil.isNull(serve) || serve.getSaleStatus() == 2) {
            throw new ForbiddenOperationException("当前服务已经是上架状态了");
        }
        //2) 服务项目是启用状态
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        if (ObjectUtil.isNull(serveItem) || serveItem.getActiveStatus() != 2) {
            throw new ForbiddenOperationException("服务项目未启用");
        }
        //3) 修改
        serve.setSaleStatus(2);
        this.updateById(serve);
        //4）添加同步表数据
        addServeSync(id);
    }

    @Autowired
    private ServeTypeMapper serveTypeMapper;

    @Autowired
    private ServeSyncMapper serveSyncMapper;

    /**
     * 添加服务同步方法
     *
     * @param serveId 服务的唯一标识符
     */
    private void addServeSync(Long serveId) {
        //服务信息
        Serve serve = baseMapper.selectById(serveId);
        //区域信息
        Region region = regionMapper.selectById(serve.getRegionId());
        //服务项信息
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        //服务类型
        ServeType serveType = serveTypeMapper.selectById(serveItem.getServeTypeId());

        ServeSync serveSync = new ServeSync();
        serveSync.setServeTypeId(serveType.getId());
        serveSync.setServeTypeName(serveType.getName());
        serveSync.setServeTypeIcon(serveType.getServeTypeIcon());
        serveSync.setServeTypeImg(serveType.getImg());
        serveSync.setServeTypeSortNum(serveType.getSortNum());

        serveSync.setServeItemId(serveItem.getId());
        serveSync.setServeItemIcon(serveItem.getServeItemIcon());
        serveSync.setServeItemName(serveItem.getName());
        serveSync.setServeItemImg(serveItem.getImg());
        serveSync.setServeItemSortNum(serveItem.getSortNum());
        serveSync.setUnit(serveItem.getUnit());
        serveSync.setDetailImg(serveItem.getDetailImg());
        serveSync.setPrice(serve.getPrice());

        serveSync.setCityCode(region.getCityCode());
        serveSync.setId(serve.getId());
        serveSync.setIsHot(serve.getIsHot());
        serveSyncMapper.insert(serveSync);
    }

    /**
     * 区域服务下架
     *
     * @param id
     */
    @Override
    public void offSale(Long id) {
        //区域服务为上架状态方可下架
        Serve serve = this.getById(id);
        if (ObjectUtil.isNull(serve) || serve.getSaleStatus() != 2) {
            throw new ForbiddenOperationException("当前服务已经是下架状态了");
        }
        serve.setSaleStatus(1);
        this.updateById(serve);
        //删除同步表数据
        serveSyncMapper.deleteById(id);
    }

    /**
     * 获取首页服务列表数据
     *
     * @param regionId 地区ID，用于筛选对应区域的服务信息
     * @return 返回首页服务列表数据，包含服务分类信息的数据传输对象集合
     */
    @Caching(
            cacheable = {
                    //返回数据为空，则缓存空值30分钟，这样可以避免缓存穿透
                    @Cacheable(value = RedisConstants.CacheName.SERVE_ICON, key = "#regionId",
                            unless = "#result.size() > 0", cacheManager = RedisConstants.CacheManager.THIRTY_MINUTES),

                    //返回值不为空，则永久缓存数据
                    @Cacheable(value = RedisConstants.CacheName.SERVE_ICON, key = "#regionId",
                            unless = "#result.size() == 0", cacheManager = RedisConstants.CacheManager.FOREVER)
            })
    @Override
    public List<ServeCategoryResDTO> firstPageServeList(Long regionId) {
        //对区域进行校验
        Region region = regionMapper.selectById(regionId);
        if (ObjectUtil.isNull(region) || region.getActiveStatus() != 2) {
            return Collections.emptyList();
        }
        //查询指定区域服务分类及上架信息
        List<ServeCategoryResDTO> list = baseMapper.findListByRegionId(regionId);
        if (ObjectUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        //截取 展示2个服务类.4个服务项
        list = CollUtil.sub(list, 0, Math.min(list.size(), 2));
        list.forEach(e -> e.setServeResDTOList(CollUtil.sub(e.getServeResDTOList(), 0, Math.min(e.getServeResDTOList().size(), 4))));
        return list;
    }

    /**
     * 获取热门服务列表
     *
     * @param regionId 区域ID，用于查询指定区域内的热门服务
     * @return 返回热门服务列表，列表中的每个元素都是ServeAggregationSimpleResDTO类型
     */
    @Cacheable(value = RedisConstants.CacheName.HOT_SERVE, key = "#regionId")
    @Override
    public List<ServeAggregationSimpleResDTO> hotServeList(Long regionId) {
        //对区域进行校验
        Region region = regionMapper.selectById(regionId);
        if (ObjectUtil.isNull(region) || region.getActiveStatus() != 2) {
            return Collections.emptyList();
        }
        return baseMapper.findServeListByRegionId(regionId);
    }

    /**
     * 根据ID查询服务聚合简单结果DTO
     *
     * @param id 查询条件的唯一标识符
     * @return 返回服务聚合简单结果DTO对象，包含查询到的相关信息
     */
    @Override
    public ServeAggregationSimpleResDTO findById(Long id) {
        //根据服务id查询服务表信息
        Serve serve = this.getById(id);
        if (ObjectUtil.isNull(serve) || serve.getSaleStatus() != 2) {
            throw new ForbiddenOperationException("服务不存在或已下架");
        }
        //根据服务项id查询服务项表信息
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        if (ObjectUtil.isNull(serveItem) || serveItem.getActiveStatus() != 2) {
            throw new ForbiddenOperationException("服务项不存在或未启用");
        }
        //将2部分组装起来返回结果
        ServeAggregationSimpleResDTO dto = new ServeAggregationSimpleResDTO();
        dto.setId(serve.getId());
        dto.setServeItemId(serveItem.getId());
        dto.setServeItemName(serveItem.getName());
        dto.setServeItemImg(serveItem.getImg());
        dto.setUnit(serveItem.getUnit());
        dto.setPrice(serve.getPrice());
        dto.setDetailImg(serveItem.getDetailImg());
        dto.setCityCode(serve.getCityCode());


        return dto;
    }

    /**
     * 根据地区ID获取服务类型聚合列表
     *
     * @param regionId 地区ID，用于筛选特定区域的服务类型
     * @return 返回服务类型聚合简化响应DTO列表，包含服务类型的基本信息
     */
    @Override
    public List<ServeAggregationTypeSimpleResDTO> serveTypeList(Long regionId) {
        //对区域进行校验
        Region region = regionMapper.selectById(regionId);
        if (ObjectUtil.isNull(region) || region.getActiveStatus() != 2) {
            return Collections.emptyList();
        }
        return baseMapper.findServeTypeListByRegionId(regionId);
    }

    /**
     * 根据城市编码、关键词和服务类型ID搜索服务信息
     *
     * @param cityCode    城市编码，用于限定搜索的城市范围
     * @param keyword     搜索关键词，用于匹配服务名称或描述等信息
     * @param serveTypeId 服务类型ID，用于筛选特定类型的服务
     * @return 返回符合条件的服务列表，每个服务以ServeSimpleResDTO对象形式返回
     */
    @Autowired
    private RestHighLevelClient client;
    @Override
    public List<ServeSimpleResDTO> search(String cityCode, String keyword, Long serveTypeId) throws IOException {
        //1.创建请求对象
        SearchRequest request = new SearchRequest("serve_aggregation");
        //2.设置请求参数
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must(QueryBuilders.termQuery("city_code",cityCode));//指定城市
        if (ObjectUtil.isNotNull(serveTypeId)){
            boolQuery.must(QueryBuilders.termQuery("serve_type_id",serveTypeId));//服务类型
        }
        if (ObjectUtil.isNotEmpty(keyword)){
            boolQuery.must(QueryBuilders.multiMatchQuery(keyword,"serve_item_name","serve_type_name"));//分词查询服务类型服务项目名称
        }
        request.source().query(boolQuery);
        request.source().sort("serve_item_sort_num", SortOrder.ASC);//排序
        request.source().from(0).size(100);//分页
        //3.发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //4.处理返回结果
        List<ServeSimpleResDTO> collect = Arrays.stream(response.getHits().getHits()).map(e -> {
            ServeSync serveSync = JSON.parseObject(e.getSourceAsString(), ServeSync.class);
            return BeanUtil.copyProperties(serveSync, ServeSimpleResDTO.class);
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 根据ID查询服务详情
     *
     * @param id 服务id
     * @return 服务详情
     */
    @Override
    public ServeAggregationResDTO findServeDetailById(Long id) {
        return baseMapper.findServeDetailById(id);
    }
}
